<?php

/**
 *
 * @todo : 暂不支持多文件上传
 */

namespace App\Helper;

/*
Demo:

$upload = new Upload('pic', array('png', 'bmp', 'gif', 'jpeg', 'jpg'));
if (!$upload->isSUCCEED())
{
    $upload->throwError();
}
$upfile = $upload->moveToDirectory('/home/www/attachment/', md5(microtime(1)));


*/

class Upload
{
    protected $errInfo = array(
        UPLOAD_ERR_EXTENSION => '',
        UPLOAD_ERR_INI_SIZE => '超过配置文件设置大小',
        UPLOAD_ERR_FORM_SIZE => '',
        UPLOAD_ERR_PARTIAL => '',
        UPLOAD_ERR_NO_FILE => '',
        UPLOAD_ERR_NO_TMP_DIR => '',
        UPLOAD_ERR_CANT_WRITE => '',
    );

    protected $formFieldName = 'uploadfile';

    protected $allowTypeList = array();

    public function __construct($fieldName = 'uploadfile', $allowType = NULL)
    {
        $this->formFieldName = $fieldName;

        if (NULL !== $allowType)
        {
            $this->addAllowType($allowType);
        }
    }

    public function moveToDirectory($dir, $newFile)
    {
        $filename = $_FILES[$this->formFieldName]['tmp_name'];
        $suffix   = $this->getSuffix($filename);

        $targetFile = rtrim($dir, DS) . "/{$newFile}.{$suffix}";
        if (is_uploaded_file($filename) && $this->checkType($suffix))
        {
            move_uploaded_file($filename, $targetFile);
            return $targetFile;
        }
        else
        {
            $this->throwError('上传文件异常或目标文件错误');
        }
    }

    public function checkType($type)
    {
        return in_array($type, $this->allowTypeList);
    }

    protected function getSuffix($filename)
    {
        return $suffix;
    }

    public function addAllowType($types)
    {
        if (is_array($types))
        {
            $this->allowTypeList += $types;
        }
        else
        {
            array_push($this->allowTypeList, $types);
        }
    }

    public function isSUCCEED()
    {
        return $_FILES[$this->formFieldName]['error'] === UPLOAD_ERR_OK;
    }

    public function throwError($info = '')
    {
        if ('' !== $info)
        {
            throw new ErrorException($info);
        }
        elseif (isset($this->errInfo[$_FILES[$this->formFieldName]['error']]))
        {
            throw new ErrorException($this->errInfo[$_FILES[$this->formFieldName]['error']]);
        }

        throw new ErrorException('未知错误');
    }
}